package com.simafei.flow.web.util;

import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @author fengpengju
 */
public class DownloadUtils {

    public static ResponseEntity<ByteArrayResource> toResponseEntity(String fileName, String content) {
        ByteArrayResource resource = new ByteArrayResource(content.getBytes(StandardCharsets.UTF_8)) {
            @Override
            public String getFilename() {
                return fileName;
            }
        };

        // 设置HTTP响应头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment", resource.getFilename());
        headers.setAccessControlExposeHeaders(List.of(HttpHeaders.CONTENT_DISPOSITION));
        headers.setContentType(MediaType.TEXT_PLAIN);

        // 返回带有Content-Disposition头的HTTP响应
        return ResponseEntity.ok()
                .headers(headers)
                .contentLength(resource.contentLength())
                .body(resource);
    }
}
